#!/bin/bash

# set -e

echo -e "\n1.查看 Volume:"
lsblk

echo -e "\n2.查看文件系统:"
df -Th

echo -e "\n3.分区 Partition 应用 Volume"
VOLUME=""
PARTITION=""

VOLUME1=/dev/nvme0n1
VOLUME2=/dev/xvda
VOLUME3=/dev/vda

df -Th | grep $VOLUME1 >>/dev/null 2>&1
if [ "$?" = "0" ] && [ "$VOLUME" = "" ]; then
  VOLUME=$VOLUME1
  PARTITION=${VOLUME}p1
fi

df -Th | grep $VOLUME2 # >> /dev/null 2>&1
if [ "$?" = "0" ] && [ "$VOLUME" = "" ]; then
  VOLUME=$VOLUME2
  PARTITION=${VOLUME}1
fi

df -Th | grep $VOLUME3 # >> /dev/null 2>&1
if [ "$?" = "0" ] && [ "$VOLUME" = "" ]; then
  VOLUME=$VOLUME3
  PARTITION=${VOLUME}1
fi

if [ "$VOLUME" = "" ]; then
  echo -e "\nCannot found volume can be resize.\n"
  lsblk
  echo ""
  exit 1
fi

# WARN: unknown label
#   failed [sfd_dump:1] sfdisk --unit=S --dump /dev/xvda1
#   sfdisk: /dev/xvda1: does not contain a recognized partition table
#   FAILED: failed to dump sfdisk info for /dev/xvda1
# [SOLVED]
#   AWS: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/recognize-expanded-volume-linux.html?icmpid=docs_ec2_console
#   StackOverflow: https://stackoverflow.com/questions/24014493/unable-to-resize-root-partition-on-ec2-centos/38463651#38463651
sudo growpart $VOLUME 1

# XFS
# which xfs_growfs >> /dev/null 2>&1
cat /etc/fstab | grep xfs >>/dev/null 2>&1
if [ "$?" = "0" ]; then
  sudo xfs_growfs -d / >>/dev/null
  echo -e "\n4.(XFS) Resize Disk Successfully"
  df -h
  exit 0
fi

# EXT4
# which resize2fs >> /dev/null 2>&1
cat /etc/fstab | grep ext4 >>/dev/null 2>&1
if [ "$?" = "0" ]; then
  sudo resize2fs $PARTITION >>/dev/null
  echo -e "\n4.(EXT4) Resize Disk Successfully"
  df -h
  exit 0
fi

cat /etc/fstab
echo ""
log::error "Error: Unknown File System"
